package cn.nit.blog.controller;

import cn.nit.blog.dto.IndexDataDto;
import cn.nit.blog.dto.MyPage;
import cn.nit.blog.entity.User;
import cn.nit.blog.service.IPostService;
import cn.nit.blog.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * Created by wjx on 2023/3/23 11:45
 */
@Controller
public class IndexController {

    @Value("${blog.login.auto}")
    private boolean autoLogin;

    @Value("${blog.login.id}")
    private Integer userId;

    @Autowired
    private IUserService userService;

    @Autowired
    private IPostService postService;

    @GetMapping("/")
    public String index(HttpSession session,
                        Model model,
                        MyPage<IndexDataDto> page,
                        @RequestParam(defaultValue = "1") Integer orderMode){

        Object loginUser = session.getAttribute("loginUser");
        if (loginUser == null) {
            autoLogin();
        }

//        将数据放在model中，刷新帖子
        MyPage<IndexDataDto> indexDataDtoMyPage = postService.indexPost(page, orderMode);
        model.addAttribute("page",indexDataDtoMyPage);

        return "index";
    }

    public void autoLogin() {
        if (autoLogin){
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpSession session = requestAttributes.getRequest().getSession();
//            自动登录
            User user = userService.getById(userId);
            user.setPassword(null);
            session.setAttribute("loginUser",user);
        }
    }

}
